import 'package:flutter/material.dart';
import 'package:netflix_social/constants/app_constants.dart';
import 'package:netflix_social/models/social_post.dart';
import 'package:netflix_social/providers/social_provider.dart';
import 'package:netflix_social/providers/auth_provider.dart';
import 'package:netflix_social/theme/app_theme.dart';
import 'package:netflix_social/widgets/social_post_card.dart';
import 'package:provider/provider.dart';

class SocialTab extends StatefulWidget {
  const SocialTab({Key? key}) : super(key: key);

  @override
  State<SocialTab> createState() => _SocialTabState();
}

class _SocialTabState extends State<SocialTab> with SingleTickerProviderStateMixin {
  late TabController _tabController;
  final TextEditingController _postController = TextEditingController();
  bool _isComposing = false;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();
    _postController.dispose();
    super.dispose();
  }

  void _toggleComposePost() {
    setState(() {
      _isComposing = !_isComposing;
    });
  }

  Future<void> _submitPost() async {
    if (_postController.text.trim().isEmpty) return;

    final socialProvider = Provider.of<SocialProvider>(context, listen: false);
    await socialProvider.createPost(content: _postController.text.trim());
    
    if (mounted) {
      _postController.clear();
      setState(() {
        _isComposing = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final socialProvider = Provider.of<SocialProvider>(context);
    final authProvider = Provider.of<AuthProvider>(context);
    
    return Scaffold(
      backgroundColor: AppTheme.backgroundColor,
      appBar: AppBar(
        backgroundColor: AppTheme.backgroundColor,
        elevation: 0,
        title: Text(
          '影享圈',
          style: Theme.of(context).textTheme.headlineSmall,
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.notifications_none),
            onPressed: () {
              Navigator.pushNamed(context, AppConstants.notificationsRoute);
            },
          ),
          IconButton(
            icon: const Icon(Icons.search),
            onPressed: () {
              Navigator.pushNamed(context, AppConstants.searchRoute);
            },
          ),
        ],
        bottom: TabBar(
          controller: _tabController,
          indicatorColor: AppTheme.netflixRed,
          labelColor: Colors.white,
          unselectedLabelColor: Colors.grey,
          tabs: const [
            Tab(text: '热门'),
            Tab(text: '关注'),
            Tab(text: '发现'),
          ],
        ),
      ),
      floatingActionButton: !_isComposing
          ? FloatingActionButton(
              onPressed: _toggleComposePost,
              backgroundColor: AppTheme.netflixRed,
              child: const Icon(Icons.add),
            )
          : null,
      body: Stack(
        children: [
          TabBarView(
            controller: _tabController,
            children: [
              // 热门动态
              _buildPostsList(socialProvider.trendingPosts),
              // 关注动态
              _buildPostsList(socialProvider.followingPosts),
              // 发现动态
              _buildPostsList(socialProvider.discoverPosts),
            ],
          ),
          // 发布动态
          if (_isComposing)
            _buildComposePostOverlay(context, authProvider.currentUser),
        ],
      ),
    );
  }

  Widget _buildPostsList(List<SocialPost> posts) {
    if (posts.isEmpty) {
      return const Center(
        child: Text('暂无动态'),
      );
    }

    return ListView.builder(
      padding: const EdgeInsets.only(bottom: 80),
      itemCount: posts.length,
      itemBuilder: (context, index) {
        return SocialPostCard(
          post: posts[index],
          onTap: () {
            // 点击帖子详情
            // 实际项目中，这里可能会导航到帖子详情页面
          },
          onVideoTap: posts[index].relatedVideo != null
              ? () {
                  Navigator.pushNamed(
                    context,
                    AppConstants.videoDetailRoute,
                    arguments: posts[index].relatedVideo!.id,
                  );
                }
              : null,
          onLikeTap: () {
            final socialProvider = Provider.of<SocialProvider>(context, listen: false);
            socialProvider.toggleLike(posts[index].id);
          },
          onCommentTap: () {
            _showCommentBottomSheet(context, posts[index]);
          },
          onShareTap: () {
            // 分享
            // 实际项目中，这里可能会调用分享功能
          },
        );
      },
    );
  }

  Widget _buildComposePostOverlay(BuildContext context, user) {
    return Container(
      color: AppTheme.backgroundColor,
      child: Column(
        children: [
          // 顶部导航
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                  color: AppTheme.dividerColor,
                  width: 0.5,
                ),
              ),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                TextButton(
                  onPressed: _toggleComposePost,
                  child: const Text('取消'),
                ),
                TextButton(
                  onPressed: _submitPost,
                  child: const Text(
                    '发布',
                    style: TextStyle(
                      color: AppTheme.netflixRed,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ],
            ),
          ),
          // 用户信息
          Padding(
            padding: const EdgeInsets.all(16),
            child: Row(
              children: [
                CircleAvatar(
                  backgroundImage: NetworkImage(user.avatar),
                  radius: 20,
                ),
                const SizedBox(width: 12),
                Text(
                  user.username,
                  style: Theme.of(context).textTheme.titleMedium,
                ),
              ],
            ),
          ),
          // 输入框
          Expanded(
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: TextField(
                controller: _postController,
                maxLines: null,
                decoration: const InputDecoration(
                  hintText: '分享你的观影感受...',
                  border: InputBorder.none,
                ),
                autofocus: true,
              ),
            ),
          ),
          // 底部选项
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              border: Border(
                top: BorderSide(
                  color: AppTheme.dividerColor,
                  width: 0.5,
                ),
              ),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                _buildComposeOption(Icons.movie, '关联影片'),
                _buildComposeOption(Icons.image, '添加图片'),
                _buildComposeOption(Icons.emoji_emotions, '表情'),
                _buildComposeOption(Icons.location_on, '位置'),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildComposeOption(IconData icon, String label) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Icon(
          icon,
          color: Colors.grey,
        ),
        const SizedBox(height: 4),
        Text(
          label,
          style: const TextStyle(
            color: Colors.grey,
            fontSize: 12,
          ),
        ),
      ],
    );
  }

  void _showCommentBottomSheet(BuildContext context, SocialPost post) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: AppTheme.cardColor,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(
          top: Radius.circular(16),
        ),
      ),
      builder: (context) {
        return DraggableScrollableSheet(
          initialChildSize: 0.7,
          minChildSize: 0.5,
          maxChildSize: 0.9,
          expand: false,
          builder: (context, scrollController) {
            return Column(
              children: [
                // 顶部把手
                Container(
                  width: 40,
                  height: 4,
                  margin: const EdgeInsets.symmetric(vertical: 12),
                  decoration: BoxDecoration(
                    color: Colors.grey[600],
                    borderRadius: BorderRadius.circular(2),
                  ),
                ),
                // 标题
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 16),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        '评论 (${post.comments.length})',
                        style: Theme.of(context).textTheme.titleMedium,
                      ),
                      IconButton(
                        icon: const Icon(Icons.close),
                        onPressed: () {
                          Navigator.pop(context);
                        },
                      ),
                    ],
                  ),
                ),
                // 评论列表
                Expanded(
                  child: ListView.builder(
                    controller: scrollController,
                    padding: const EdgeInsets.all(16),
                    itemCount: post.comments.length,
                    itemBuilder: (context, index) {
                      final comment = post.comments[index];
                      return Padding(
                        padding: const EdgeInsets.only(bottom: 16),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            CircleAvatar(
                              backgroundImage: NetworkImage(comment.author.avatar),
                              radius: 16,
                            ),
                            const SizedBox(width: 12),
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    comment.author.username,
                                    style: const TextStyle(
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                  const SizedBox(height: 4),
                                  Text(comment.content),
                                  const SizedBox(height: 4),
                                  Row(
                                    children: [
                                      Text(
                                        comment.createdAt.toString().substring(0, 16),
                                        style: const TextStyle(
                                          color: Colors.grey,
                                          fontSize: 12,
                                        ),
                                      ),
                                      const SizedBox(width: 12),
                                      const Text(
                                        '回复',
                                        style: TextStyle(
                                          color: Colors.grey,
                                          fontSize: 12,
                                        ),
                                      ),
                                      const Spacer(),
                                      const Icon(
                                        Icons.favorite_border,
                                        size: 16,
                                        color: Colors.grey,
                                      ),
                                      const SizedBox(width: 4),
                                      Text(
                                        '${comment.likeCount}',
                                        style: const TextStyle(
                                          color: Colors.grey,
                                          fontSize: 12,
                                        ),
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      );
                    },
                  ),
                ),
                // 评论输入框
                Container(
                  padding: const EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    border: Border(
                      top: BorderSide(
                        color: AppTheme.dividerColor,
                        width: 0.5,
                      ),
                    ),
                  ),
                  child: Row(
                    children: [
                      Expanded(
                        child: TextField(
                          decoration: InputDecoration(
                            hintText: '发表评论...',
                            contentPadding: const EdgeInsets.symmetric(
                              horizontal: 16,
                              vertical: 8,
                            ),
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(20),
                              borderSide: BorderSide.none,
                            ),
                            filled: true,
                            fillColor: Colors.grey[800],
                          ),
                        ),
                      ),
                      const SizedBox(width: 8),
                      IconButton(
                        icon: const Icon(Icons.send),
                        color: AppTheme.netflixRed,
                        onPressed: () {
                          // 发送评论
                          // 实际项目中，这里可能会调用发送评论的方法
                          Navigator.pop(context);
                        },
                      ),
                    ],
                  ),
                ),
              ],
            );
          },
        );
      },
    );
  }
}
